package com.zysdev.opengldemo

import android.graphics.SurfaceTexture
import android.opengl.GLSurfaceView
import androidx.camera.core.Preview
import androidx.lifecycle.LifecycleOwner
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class CameraRender : GLSurfaceView.Renderer, Preview.OnPreviewOutputUpdateListener,
    SurfaceTexture.OnFrameAvailableListener {

    private var cameraView: CameraView? = null

    private var surfaceTexture: SurfaceTexture? = null
    private val textures: IntArray = IntArray(1)

    private var screenFilter: ScreenFilter? = null

    private var mtx = FloatArray(16)

    constructor(cameraView: CameraView) {
        this.cameraView = cameraView
        val lifecycleOwner = cameraView.context as LifecycleOwner
        //打开摄像头
        CameraHelper(lifecycleOwner, this)


    }

    // 打开摄像头后，摄像头预览到的数据通过接口回调到这里
    override fun onUpdated(output: Preview.PreviewOutput?) {
        //获取到摄像头的预览数据，数据在surfaceTexture里
        surfaceTexture = output?.surfaceTexture

    }

    override fun onSurfaceCreated(p0: GL10?, p1: EGLConfig?) {
//        1
//    将摄像头的数据给GPU    让 SurfaceTexture   与 Gpu  共享一个数据源  0-31
        //绑定摄像头和GPU，此时会在GPU创建一个内存
        surfaceTexture?.attachToGLContext(textures[0])

        //当有数据过来时的回调
        surfaceTexture?.setOnFrameAvailableListener(this)

        screenFilter = ScreenFilter(cameraView!!.context)

    }

    override fun onSurfaceChanged(p0: GL10?, width: Int, height: Int) {
        screenFilter?.setSize(width, height)
    }

    //这里的线程是GLThread
    //当GLSurfaceView重新渲染时requestRender()，会回调到这里
    override fun onDrawFrame(p0: GL10?) {

        //        更新数据
        surfaceTexture?.updateTexImage()

        //将图像的矩阵信息保存到mtx中
        surfaceTexture?.getTransformMatrix(mtx)

        screenFilter?.setTransformMatrixAndDraw(mtx,textures[0])
    }


    //SurfaceTexture里有数据时
    override fun onFrameAvailable(p0: SurfaceTexture?) {
        //让cameraView手动刷新
        cameraView?.requestRender()
    }
}